package task

import (
	"context"
	"demo/domain/service"
	"demo/infra/middleware/task"
	"github.com/go-redis/redis/v8"
	"go.uber.org/zap"
	"time"
)

type BusinessTask struct {
	statisticsService *service.StatisticsService
	redisClient       *redis.Client
	logger            *zap.Logger
}

func NewBusinessTask(redisClient *redis.Client, logger *zap.Logger, statisticsService *service.StatisticsService) *BusinessTask {
	return &BusinessTask{redisClient: redisClient, statisticsService: statisticsService, logger: logger}
}

func (bs *BusinessTask) InitTask() {
	// 创建任务管理器
	taskManager := task.NewTaskManager(bs.redisClient, bs.logger)
	// 添加任务1：每日URL访问统计（每天凌晨2点执行）
	taskManager.AddTask(
		"url_statistics_daily",
		24*time.Hour,
		func(ctx context.Context) error {
			// 获取当前时间（本地时区）
			now := time.Now()
			// 转换为UTC时间后再计算
			utcNow := now.UTC()
			start := utcNow.AddDate(0, 0, -1).Truncate(24 * time.Hour)
			end := start.Add(24*time.Hour - time.Nanosecond)
			return bs.statisticsService.ProcessVisitStatisticsDuration(ctx, start, end)
		},
	)
	// 添加任务2：每小时清理过期短链（每小时执行一次）
	/*taskManager.AddTask(
		"clean_expired_shorturls",
		time.Minute,
		func(ctx context.Context) error {
			bs.logger.Info("clean_expired_shorturls")
			return nil
		},
	)*/
	// 启动所有定时任务
	go taskManager.StartAll()
	defer taskManager.StopAll()
}
